/*
 * bFocus 1.4
 * Copyright (c) 2014 Bill QQ:378112711
 * Date: 2014-02-20
 * 例：
 * $('.xxxx').bFocus({
 *   width:滚动区宽度,
 *   height:滚动区高度,
 *   direction:'top',//默认：0(谈入谈出)，left(左滚动)，top（上滚动）
 *   slt:1, //焦点图下面出现缩略图导航
 *   ....
 *   ....
 *   ....
 * });
 */
(function(factory){
    if(typeof define === 'function' && define.amd){
        define(['jquery'],factory);
    }else{
        factory(window.jQuery);
    }
}(function($) {
	$.fn.bFocus = function(o) {
        var opts = $.extend({},$.fn.bFocus.defaults, o);
        return this.each(function() {
            var obj = $(this);
            switch(opts.direction){
                case 'top': opts.direction = 1; break;
                case 'right': opts.direction = 2; break;
                case 'bottom' : opts.direction = 3; break;
                case 'left' : opts.direction = 4; break;
            }
            var _objcss = {'width': opts.width,'height': opts.height,'overflow':"hidden"};
            obj.css(_objcss);
            if(obj.find(".bfocus_wrap").length==0){
            obj.wrapInner($('<div class="bfocus_wrap"/>'));
            }
            var bwrap = obj.find(".bfocus_wrap");
            var ulw=0;
            if (opts.n === 0){
                var li = bwrap.find("a");
                bwrap.find('a').css(_objcss);
            }else{
                //opts.speed=opts.pause;
                if(opts.direction === 2 || opts.direction === 4) bwrap.find("ul").css('float','left');
                var li=bwrap.find("li");
                bwrap.find('ul').clone(true).appendTo(bwrap);
            }
            var s = li.length;
            if(s==0) return false;
            var curr = 0, timer = 0, totalw = 0, p = 0;
            var step = opts.step;
            if (opts.n === 0 && (opts.direction === 1 || opts.direction === 3)) {step = opts.height;}
            if (opts.n === 0 && (opts.direction === 2 || opts.direction === 4)) {step = opts.width;}
            if(opts.btn){
                var btn = $(opts.btn);
            }else{
                var btn = obj;
            }
            if (opts.direction === 0) {
                li.css({'position': 'absolute','top': '0px','left': '0px'});
            } else {
                li.show();
                if(opts.n === 1){
                    if(opts.direction === 2 || opts.direction === 4)
                    bwrap.find("li").css({"float": "left"});
                }else{
                    li.css({"float": "left"});
                }
            }
            if (opts.direction === 1 || opts.direction === 3) {
                var g=(li[0].offsetHeight+parseInt($.css(li[0], 'marginTop'))+parseInt($.css(li[0],'marginBottom')));
                var i=1;
                if (opts.n === 0){ totalw = opts.height * s; }else{
                    totalw= g * s;
                    if(opts.n===1){
                        i=2;
                        if(opts.height>totalw){ bwrap.find('ul:last').remove(); return false; }
                    }
                }
                bwrap.css({'width': opts.width,'height': totalw*i});
            }
            if (opts.direction === 2 || opts.direction === 4) {
                var g=(li[0].offsetWidth+parseInt($.css(li[0], 'marginLeft'))+parseInt($.css(li[0],'marginRight')));
                var i=1;
                if (opts.n === 0){ totalw=opts.width * s; }else{
                    totalw = g * s;
                    if(opts.n===1){
                        i=2;
                        if(opts.width>totalw){ bwrap.find('ul:last').remove(); return false; }
                    }
                }
                bwrap.css({'width': totalw*i ,'height': opts.height});


            }
            var totalp=0;
            if (opts.direction === 0) {
                totalp=s;
            }else{
                if(totalw % step){
                    totalp=parseInt(totalw / step)+1;
                }else{
                    totalp=parseInt(totalw / step);
                }
            }
            if ((opts.type === 1 || opts.type === 3) && s > 0) {
                var titlehtml = $('<div class="link_nav">');
                for (var i = 0; i < s; i++) {
                    var items = li.eq(i);
                    titlehtml.append('<a href="' + items.attr("href") + '" target="_blank">' + items.attr("title") + '</a>');
                }
                titlehtml.append('<span></span>');
                obj.append(titlehtml);
                obj.find(".link_nav a:not(:first)").hide();
            }
            if ((opts.type === 2 || opts.type === 3) && s > 1) {
                var navhtml = $('<div class="num_nav">');
                for (var j = 0; j < s; j++) {
                    navhtml.append('<span>' + (j + 1) + '</span>');
                }
                btn.append(navhtml);
                btn.find(".num_nav span").hover(function() {
                    var num = $(this).html();
                    Play(num-1, true);
                },function() {
                    timer = setTimeout(function(){ Play(curr, false);}, opts.pause);
                });
            }
            if(opts.slt===1){
                var sltw=parseInt(opts.width*opts.scale/10);
                var slth=parseInt((opts.height*sltw)/opts.width);

                var slthtml = $('<div class="slt_nav">');
                for (var i = 0; i < s; i++) {
                    items = li.eq(i);
                    var slts=' style="width:'+sltw+'px;height:'+slth+'px"';
                    slthtml.append('<a href="javascript:;" x="'+(i + 1)+'"'+slts+'>'
                              + '<img src="' + items.find("img").attr("src") + '"'+slts+'/>'
                              + '<span'+slts+'></span>'
                              + '</a>');
                }
                obj.append(slthtml);
                obj.find(".slt_nav a").click(function(){
                    var num = $(this).attr("x");Play(num-1,true);
                    timer = setTimeout(function(){ Play(curr, false);}, opts.pause);
                });
            }
            function setcurrnum(t,x) {
                if (opts.slt === 1){
                    var sw=obj.find(".slt_nav a").width();
                    obj.find(".slt_nav a").eq(t).addClass("ns").siblings().removeClass('ns');
                    obj.find(".slt_nav span").stop().css({"width":sw+"px"}).eq(t).css({"width":"0px"});
                }
                if ((opts.type === 2 || opts.type === 3) && s > 1) {
                    btn.find(".num_nav span").eq(t).addClass('selected').siblings().removeClass('selected');
                }
                if ((opts.type === 1 || opts.type === 3) && s > 0) {
                    obj.find(".link_nav a").filter(":visible").fadeOut(500).parent().children().eq(t).fadeIn(1000);
                }

                if(opts.direction!=0){
                    p = (t * step * -1);
                }
                switch(opts.direction){
                    case 1:
                    case 3:
                        if(opts.n === 1 && parseInt(t * step)==0){
                            bwrap.stop().css({marginTop: "0px"});
                        }else{
                            bwrap.stop().animate({marginTop: p + "px"},opts.speed);
                        }
                        break;
                    case 2:
                    case 4:
                        if(opts.n === 1 && parseInt(p)==0){
                            bwrap.stop().css({marginLeft: "0px"});
                        }else{
                            bwrap.stop().animate({marginLeft: p + "px"},opts.speed);
                        }
                        break;
                    default:
                        if(x===1){
                            obj.find(".bfocus_wrap a").filter(":visible").fadeOut(500).parent().children().eq(t).fadeIn(1000);
                        }else{
                            obj.find(".bfocus_wrap a").hide().parent().children().eq(t).show();
                        }
                }
            }
            function Play(t, clicked) {
                t=parseInt(t);
                if(opts.n===1){
                    if(t>=(totalp+1) || t<0){t=0;}
                    curr = t === (totalp+1)? 0:t;
                    var next=curr+1;
                    next= next === (totalp+1)?0:next;
                }else{
                    if(t>=totalp || t<0){t=0;}
                    curr = t === totalp? 0:t;
                    var next=curr+1;
                    next= next === totalp?0:next;
                }
                setcurrnum(t,1);
                if (clicked) {clearTimeout(timer);}
                if (opts.auto && !clicked) { timer = setTimeout(function() {Play(next, false);},opts.pause);}
            }
            $(bwrap).hover(function(){
                clearTimeout(timer);
            },function(){
                clearTimeout(timer);Play(curr+1, false);
            });
            if (opts.prev) $(opts.prev).click(function(){clearTimeout(timer);Play(curr-1, false);});
            if (opts.next) $(opts.next).click(function(){clearTimeout(timer);Play(curr+1, false);});
            setcurrnum(0,0);
            if (opts.auto && s > 1) {timer = setTimeout(function() {Play(1, false);},opts.pause);}
        });
    };
    $.fn.bFocus.defaults = {
        width: '',    //滚动区宽度
        height: '',   //滚动区高度
        direction: 0, //动画效果 默认：0(谈入谈出)，left(左滚动)，top（上滚动）
        type: 0,      //显示按钮,文字标题：0(都不显示), 1(只显文字标题), 2(只显按钮), 3(都显示)
        speed: 800,   //动画速度
        auto: true,   //是否自动滚动
        pause: 3000,  //切换时间
        n:0,          //0:单张图片切换，1:多张图片切换（多用于产品滚动效果）
        step:0,       //每次移动多少像素
        prev: null,   //左滚动按钮
        next: null,   //右滚动按钮
        slt:0,        //0：关闭缩略图，1：打开缩略图
        scale:1,      //缩略图显示比例
        btn : ''      //数字按钮显示位置
    };
	
	$.fn.homeslide = function(o) {
		var opt = $.extend({},o);
		return this.each(function() {
			var t = $(this),i=0,timer=null;
            $(t).append('<ul class="banner_m"></ul>');
            
            
            $(window).off("scroll resize").on("scroll resize",function(){
                var wl=$(this).scrollLeft();
                t.css({'width':wl+$(this).width()});
            });
            $(window).resize();
            
            if(opt.prev && opt.next){
                $(t).append('<div id="navigateLeft"></div><div id="navigateRight"></div>');
                t.hover(function(){
                    $(opt.prev).stop(true,true).fadeIn();
                    $(opt.next).stop(true,true).fadeIn();
                },function(){
                    $(opt.prev).stop(true,true).fadeOut(2000);
                    $(opt.next).stop(true,true).fadeOut(2000);
                });
            }            
            
            opt.pause=opt.pause||3000;
			var s=opt.data.length;
            var picw=$(window).width();
            for(var k=0;k<s;k++){
                $(opt.area).append($('<li style="display:none"><a href="'+opt.data[k].url+'" style="background-image:url('+opt.data[k].pic+');" target="_blank"></a></li>'));                
            }
            if(s>1){
                var bnav=$('<div class="bnav"></div>');
                t.append(bnav);
                for(var j=0;j<s;j++){
                    var a=$('<a href="javascript:;" />');
                    bnav.append(a);
                }
                bnav.css('margin-left',-(bnav.width()/2));
                bnav.find('a').click(function(){
                    clearTimeout(timer);
					
                    i=$(this).index();play();
                });
            }
			play=function(){
				var x=i=i>=s?0:i;
				x=i=x<0?s-1:x;
				if(s>1){
					bnav.find('a').eq(x).addClass('selected').siblings().removeClass('selected');
				}
                t.find('.info').css({'top':-1500+"px"});
                t.find(opt.area+' li').eq(x).fadeIn().siblings().fadeOut(); 
               
				i++;
                if(s>1 && opt.auto){
                    timer=setTimeout(function(){ play(); },opt.pause);
                }
			};			
            if (opt.prev) $(opt.prev).click(function(){clearTimeout(timer);i-=2;play();});
			if (opt.next) $(opt.next).click(function(){clearTimeout(timer);play();});
            if(s>0)	play();
		});
	};
}));